package ru.ifmo.croak.impl.storage.team1.stub;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.api.*;

import java.util.ArrayList;
import java.util.List;

public class StorageImpl implements PostService, QueryService {
    static Logger LOGGER = LoggerFactory.getLogger(StorageImpl.class);

    public StorageImpl(String name) {
        LOGGER.info("creating " + name + hashCode());
        messages = new ArrayList<Message>();
        listeners = new ArrayList<MessageListener>();
    }

    ArrayList<Message> messages;
    ArrayList<MessageListener> listeners;

    public void postMessage(Message message) {
        LOGGER.trace("posting " + message);
        synchronized (messages) {
            for (Message msg : messages) {
                if (msg.getId().equals(message.getId())) {
                    return;
                }
            }
            messages.add(message);
        }
        synchronized (listeners) {
            LOGGER.trace("listeners " + listeners);
            for (MessageListener ml : listeners) {
                LOGGER.trace("notify " + ml);
                ml.messageAvailable(message);
            }
        }
        LOGGER.debug("posted " + message);
    }


    public MessageQuery createQuery(final QueryRequest request) {
        LOGGER.trace("quering" + request);
        final ArrayList<Message> arrayList = new ArrayList<Message>(messages);
        return new MessageQuery() {
            public QueryRequest getRequest() {
                return request;
            }

            public List<Message> getMessages() {
                return arrayList;
            }

            public void close() {
            }

            public void setMessageListener(MessageListener listener) {
                LOGGER.trace("setMessageListener " + listener);
                synchronized (listeners) {
                    listeners.add(listener);
                }
            }
        };
    }
}
